<template>
  <div id="userRegisterPage">
    <h2 class="title">用户注册</h2>
    <a-form
        style="max-width: 480px; margin: 0 auto"
        label-align="left"
        :model="formState"
        name="basic"
        :label-col="{ span: 4 }"
        :wrapper-col="{ span: 20 }"
        autocomplete="off"
        @finish="onFinish"
        @finishFailed="onFinishFailed"
    >
      <a-form-item
          label="名字"
          name="username"
          :rules="[{ required: true, message: '请输入用户名' }]"
      >
        <a-input v-model:value="formState.userName" placeholder="请输入用户名"/>
      </a-form-item>

      <a-form-item
          label="密码"
          name="password"
          :rules="[{ required: true, message: '请输入密码' }, {min:8, message: '密码不能小于8位'}]"
      >
        <a-input-password v-model:value="formState.password" placeholder="请输入密码"/>
      </a-form-item>

      <a-form-item
          label="确认密码"
          name="checkPassword"
          :rules="[{ required: true, message: '请输入确认密码' }, {min:8, message: '确认密码不能小于8位'}]"
      >
        <a-input-password v-model:value="formState.checkPassword" placeholder="请输入确认密码"/>
      </a-form-item>

      <a-form-item :wrapper-col="{ offset: 4, span: 20 }">
        <a-button type="primary" html-type="submit" @click="onHandleSubmit(formState)">注册</a-button>
      </a-form-item>
    </a-form>
  </div>

</template>
<script lang="ts" setup>
import { reactive } from 'vue';
import { userRegister } from "@/api/user";
import { message } from "ant-design-vue";
import { useRouter } from "vue-router";

const router = useRouter();

interface FormState {
  userName: string;
  password: string;
  checkPassword: String;
}

const formState = reactive<FormState>({
  userName: '',
  password: '',
  checkPassword: '',
});

/**
 * 提交表单——登录
 */
const onHandleSubmit = async (values: any) => {
  // 校验两次密码是否一致
  if(formState.password != formState.checkPassword){
    message.error("两次输出的密码不一致");
    return;
  }

  const res = await userRegister(values);
  if(res.data.code === 200 && res.data.data){
    // 注册成功,跳转登录页面
    message.success("注册成功");
    router.push({
      path: '/user/login',
      replace: true  // 点击返回不会回到上一页面
    })
  }else{
    message.error("注册失败," + res.data.msg);
  }
};

const onFinish = () => {

}

const onFinishFailed = () => {

};
</script>

<style scoped>
#userRegisterPage .title{
  margin-bottom: 16px;
  text-align: center;
}
</style>


